import Vue from "vue";
import Vuex from "vuex";
import persistence from "./persistence";
import socket from "./socket";
import players from "./modules/players";
import session from "./modules/session";
import chat from "./modules/chat";
import voiceChat from "./modules/voiceChat";
import editionJSON from "../editions.json";
// import rolesJSON from "../roles.json"; // 不再使用内置角色数据
import fabledJSON from "../fabled.json";
import jinxesJSON from "../hatred.json";

Vue.use(Vuex);

// helper functions - 现在所有角色都由用户管理，不再使用内置数据
const getRolesByEdition = () => {
  // 返回空Map，所有角色将通过用户上传添加
  console.log("📝 getRolesByEdition: 返回空Map，等待用户上传角色数据");
  return new Map();
};

const getTravelersNotInEdition = () => {
  // 返回空Map，旅行者角色也将通过用户上传添加
  console.log("📝 getTravelersNotInEdition: 返回空Map，等待用户上传旅行者数据");
  return new Map();
};

const set =
  (key) =>
  ({ grimoire }, val) => {
    grimoire[key] = val;
  };

const toggle =
  (key) =>
  ({ grimoire }, val) => {
    if (val === true || val === false) {
      grimoire[key] = val;
    } else {
      grimoire[key] = !grimoire[key];
    }
  };

const clean = (id) => id.toLocaleLowerCase().replace(/[^a-z0-9]/g, "");

const generateUniqueId = () => {
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
};

// 数字转中文
const getChineseNumber = (num) => {
  const chineseNumbers = {
    1: "first",
    2: "second",
    3: "third",
    4: "fourth",
    5: "fifth",
    6: "sixth",
    7: "seventh",
    8: "eighth",
    9: "ninth",
    10: "tenth",
    11: "eleventh",
    12: "twelfth",
    13: "thirteenth",
    14: "fourteenth",
    15: "fifteenth",
  };
  return chineseNumbers[num] || `round_${num}`;
};

// 中文转数字 - 用于解析轮次
const getNumberFromChinese = (chineseStr) => {
  const numberMap = {
    "first": 1,
    "second": 2,
    "third": 3,
    "fourth": 4,
    "fifth": 5,
    "sixth": 6,
    "seventh": 7,
    "eighth": 8,
    "ninth": 9,
    "tenth": 10,
    "eleventh": 11,
    "twelfth": 12,
    "thirteenth": 13,
    "fourteenth": 14,
    "fifteenth": 15,
  };
  
  // 如果是数字形式的round_X，提取数字
  const roundMatch = chineseStr.match(/round_(\d+)/);
  if (roundMatch) {
    return parseInt(roundMatch[1]);
  }
  
  return numberMap[chineseStr] || null;
};

// global data maps
const editionJSONbyId = new Map(
  editionJSON.map((edition) => [edition.id, edition]),
);
// rolesJSONbyId 常量已删除，现在通过 getter 动态获取角色数据
console.log("📝 不再使用静态rolesJSONbyId，角色数据完全由用户管理");
const fabled = new Map(fabledJSON.map((role) => [role.id, role]));

// jinxes
let jinxes = {};
try {
  // Note: can't fetch live list due to lack of CORS headers
  // fetch("https://bloodontheclocktower.com/script/data/hatred.json")
  //   .then(res => res.json())
  //   .then(jinxesJSON => {
  jinxes = new Map(
    jinxesJSON.map(({ id, hatred }) => [
      clean(id),
      new Map(hatred.map(({ id, reason }) => [clean(id), reason])),
    ]),
  );
  // });
} catch (e) {
  console.error("couldn't load jinxes", e);
}

// base definition for custom roles
const customRole = {
  id: "",
  name: "",
  image: "",
  ability: "",
  edition: "custom",
  firstNight: 0,
  firstNightReminder: "",
  otherNight: 0,
  otherNightReminder: "",
  reminders: [],
  remindersGlobal: [],
  setup: false,
  team: "townsfolk",
  isCustom: true,
};

export default new Vuex.Store({
  modules: {
    players,
    session,
    chat,
    voiceChat,
  },
  state: {
    grimoire: {
      isPublic: true,
      isNight: false,
      isNightOrder: false,
      isMenuOpen: false,
      isStatic: false,
      isMuted: false,
      isImageOptIn: true,
      zoom: 0,
      background: null,
    },
    modals: {
      grimoire: false,

      roles: false,
      role: false,
      reference: false,
      nightOrder: false,
      fabled: false,
      voteHistory: false,
      gameState: false,
      reminder: false,
      roleAbility: false,
    },
    edition: editionJSON[0],
    roles: getRolesByEdition(),
    travelers: getTravelersNotInEdition(),
    fabled,
    jinxes,
    session: {
      sessionId: null,
      playerId: null,
      isSpectator: false,
      isReconnecting: false,
      playerCount: 0,
      ping: null,
      nomination: null,
      lockedVote: false,
      voteHistory: [],
      distributeRoles: false,
    },
    selectedPlayer: -1, // 添加选中的玩家索引
    history: {
      events: [],
      currentRound: 1,
      currentPhase: "night",
    },
    locale: "en-US", // 添加语言设置
  },
  getters: {
    /**
     * Return all custom roles, with default values and non-essential data stripped.
     * Role object keys will be replaced with a numerical index to conserve bandwidth.
     * @param roles
     * @returns {[]}
     */
    customRolesStripped: ({ roles }) => {
      const customRoles = [];
      const customKeys = Object.keys(customRole);
      const strippedProps = [
        "firstNightReminder",
        "otherNightReminder",
        "isCustom",
      ];
      roles.forEach((role) => {
        // 验证角色对象的有效性
        if (!role || !role.id || typeof role.id !== 'string' || role.id.trim() === '') {
          console.warn("跳过无效角色对象:", role);
          return;
        }
        
        if (!role.isCustom) {
          customRoles.push({ id: role.id });
        } else {
          const strippedRole = {};
          for (let prop in role) {
            if (strippedProps.includes(prop)) {
              continue;
            }
            const value = role[prop];
            // 只传输必要字段，确保关键字段（如team, id, name）总是包含
            if (customKeys.includes(prop)) {
              // 关键字段必须包含，即使是默认值
              if (['id', 'name', 'team', 'ability'].includes(prop) || value !== customRole[prop]) {
                strippedRole[prop] = value;  // 使用属性名而不是索引
              }
            }
          }
          customRoles.push(strippedRole);
        }
      });
      return customRoles;
    },
    rolesJSONbyId: (state) => state.roles, // 返回包含所有角色（官方+自定义）的Map
  },
  mutations: {
    setZoom: set("zoom"),
    setBackground: set("background"),
    toggleMuted: toggle("isMuted"),
    toggleMenu: toggle("isMenuOpen"),
    toggleNightOrder: toggle("isNightOrder"),
    toggleStatic: toggle("isStatic"),
    toggleNight: toggle("isNight"),
    toggleGrimoire: toggle("isPublic"),
    toggleImageOptIn: toggle("isImageOptIn"),
    setLocale(state, locale) {
      state.locale = locale;
      const userStorage = require("../utils/userStorage").default;
      userStorage.setItem("language", locale);
    },
    toggleModal({ modals }, name) {
      if (name) {
        modals[name] = !modals[name];
      }
      for (let modal in modals) {
        if (modal === name) continue;
        modals[modal] = false;
      }
    },
    /**
     * Store user roles - 现在所有角色都由用户管理，支持"官方"和"自定义"类型
     * @param state
     * @param roles Array of role definitions
     */
    setCustomRoles(state, roles) {
      // 检查roles参数是否有效
      if (!roles || !Array.isArray(roles)) {
        console.warn("Invalid roles parameter:", roles);
        return;
      }

      console.log("🔄 Processing user roles:", roles.length);
      
      // 统计输入数据的完整性
      const inputWithImages = roles.filter(r => r && r.image);
      const inputWithAbilities = roles.filter(r => r && r.ability);
      const inputOfficialType = roles.filter(r => r && r.roleType === 'official');
      const inputCustomType = roles.filter(r => r && r.roleType === 'custom');
      
      console.log(`📥 输入数据统计:`);
      console.log(`   ├─ 总数: ${roles.length} 个`);
      console.log(`   ├─ 官方类型: ${inputOfficialType.length} 个`);
      console.log(`   ├─ 自定义类型: ${inputCustomType.length} 个`);
      console.log(`   ├─ 包含图片: ${inputWithImages.length} 个`);
      console.log(`   └─ 包含能力: ${inputWithAbilities.length} 个`);
      const processedRoles = roles
        // 基本数据验证和清理
        .map((role, index) => {
          // 检查role是否存在且有效
          if (!role || typeof role !== "object") {
            console.warn("❌ 无效的角色对象:", role);
            return null;
          }

          console.log(`🔍 处理角色 ${index}:`, role);

          // 处理数值索引格式的角色数据（旧格式兼容）
          if (role[0] !== undefined) {
            console.log("🔧 检测到旧格式角色数据，进行转换:", role);
            const customKeys = Object.keys(customRole);
            const mappedRole = {};
            for (let prop in role) {
              const index = parseInt(prop);
              if (!isNaN(index) && index >= 0 && index < customKeys.length) {
                const keyName = customKeys[index];
                mappedRole[keyName] = role[prop];
                console.log(`  ${prop} -> ${keyName}: ${role[prop]}`);
              }
            }
            role = mappedRole;
            console.log("🔧 转换后的角色数据:", role);
          }

          // 检查必需字段
          if (!role.id || !role.name || !role.ability || !role.team) {
            console.warn("❌ 角色缺少必需字段:", {
              id: role.id,
              name: role.name,
              hasAbility: !!role.ability,
              team: role.team
            });
            return null;
          }

          // 标准化角色数据
          const processedRole = Object.assign({}, customRole, role, {
            // 清理角色ID
            id: clean(role.id),
            // 确保角色类型
            roleType: role.roleType || 'custom',
            isCustom: (role.roleType !== 'official'), // 只有标记为官方的才不是自定义
            // 标准化数值字段
            firstNight: Math.abs(role.firstNight || 0),
            otherNight: Math.abs(role.otherNight || 0),
            // 确保数组字段
            reminders: Array.isArray(role.reminders) ? role.reminders : [],
            remindersGlobal: Array.isArray(role.remindersGlobal) ? role.remindersGlobal : [],
            // 确保布尔字段
            setup: !!role.setup
          });

          // 处理图片字段
          if (role.image) {
            processedRole.image = role.image;
            console.log(`🖼️ 角色 ${processedRole.id} 包含自定义图片:`, role.image);
          }

          console.log(`✅ 处理角色 ${processedRole.id}:`, {
            name: processedRole.name,
            team: processedRole.team,
            roleType: processedRole.roleType,
            hasImage: !!processedRole.image,
            abilityPreview: processedRole.ability?.substring(0, 50) + '...'
          });

          return processedRole;
        })
        // 过滤无效角色
        .filter((role) => role !== null)
        // 按队伍排序
        .sort((a, b) => b.team.localeCompare(a.team));
      // 分离普通角色和传奇角色
      const normalRoles = processedRoles.filter(role => role.team !== "fabled");
      const fabledRoles = processedRoles.filter(role => role.team === "fabled");
      
      // 统计最终处理结果
      const finalWithImages = normalRoles.filter(r => r.image);
      const finalWithAbilities = normalRoles.filter(r => r.ability);
      const officialRoles = normalRoles.filter(r => r.roleType === 'official');
      const customRoles = normalRoles.filter(r => r.roleType === 'custom');
      
      console.log(`📤 最终处理结果:`);
      console.log(`   ├─ 普通角色: ${normalRoles.length} 个`);
      console.log(`   │   ├─ 官方类型: ${officialRoles.length} 个`);
      console.log(`   │   └─ 自定义类型: ${customRoles.length} 个`);
      console.log(`   ├─ 传奇角色: ${fabledRoles.length} 个`);
      console.log(`   ├─ 包含图片: ${finalWithImages.length} 个`);
      console.log(`   └─ 包含能力: ${finalWithAbilities.length} 个`);

      // 详细展示所有角色信息（用于调试）
      if (normalRoles.length > 0) {
        console.log(`🎭 角色详情:`);
        normalRoles.forEach(role => {
          console.log(`   ${role.id} (${role.roleType}): ${role.name} - ${role.ability?.substring(0, 30)}...`);
        });
      }

      // 清空现有角色并重新设置，确保Vue能够检测到变化
      state.roles.clear();
      normalRoles.forEach((role) => {
        state.roles.set(role.id, role);
      });

      // 更新传奇角色
      if (fabledRoles.length > 0) {
        state.fabled = new Map(fabledRoles.map(role => [role.id, role]));
        console.log(`🌟 更新传奇角色: ${fabledRoles.length} 个`);
      } else {
        // 如果没有用户传奇角色，保留内置传奇角色
        state.fabled = new Map(fabledJSON.map((role) => [role.id, role]));
      }

      // 清空旅行者列表，现在所有旅行者都需要用户上传
      state.otherTravelers = new Map();

      // 强制触发Vue的响应式更新
      state.roles = new Map(state.roles);
      console.log("✅ 角色数据更新完成，触发Vue响应式更新");
    },
    setEdition(state, edition) {
      console.log("Setting edition:", edition.id);
      if (editionJSONbyId.has(edition.id)) {
        // 官方版本：清空角色数据，因为官方版本现在也需要用户上传
        state.edition = editionJSONbyId.get(edition.id);
        state.roles = getRolesByEdition(state.edition);
        state.otherTravelers = getTravelersNotInEdition(state.edition);
        console.log("Official edition set, roles count:", state.roles.size);
        console.log("⚠️ 官方版本也需要用户上传角色数据");
      } else {
        // 自定义版本：保留现有角色数据，不要覆盖用户已导入的角色
        const currentRolesCount = state.roles.size;
        state.edition = edition;
        console.log(`Custom edition set, preserving ${currentRolesCount} existing roles`);
        
        // 如果当前没有角色数据，才初始化为空Map
        if (currentRolesCount === 0) {
          state.roles = new Map();
          state.otherTravelers = new Map();
          console.log("No existing roles, initialized empty Maps");
        }
      }
      state.modals.edition = false;
    },
    // 历史记录相关 mutations
    addHistoryEvent(state, event) {
      const historyEvent = {
        id: generateUniqueId(),
        timestamp: Date.now(),
        round: state.history.currentRound,
        phase: state.history.currentPhase,
        ...event,
      };

      console.log(`📝 添加历史事件: ${historyEvent.action || 'unknown'}, round: ${historyEvent.round}, summary: ${historyEvent.summary || 'no summary'}`);

      // 限制记录数量为200条
      if (state.history.events.length >= 200) {
        state.history.events.shift(); // 删除最旧的记录
      }

      state.history.events.push(historyEvent);
      console.log(`📊 历史事件总数: ${state.history.events.length}`);
      
      // 保存到本地存储
      const userStorage = require("../utils/userStorage").default;
      userStorage.setItem("gameHistory", state.history.events);
    },
    undoHistoryEvent(state) {
      if (state.history.events.length > 0) {
        state.history.events.pop();
        const userStorage = require("../utils/userStorage").default;
        userStorage.setItem("gameHistory", state.history.events);
      }
    },
    addHistoryNote(state, { eventId, note }) {
      const event = state.history.events.find((e) => e.id === eventId);
      if (event) {
        event.note = note;
        const userStorage = require("../utils/userStorage").default;
        userStorage.setItem("gameHistory", state.history.events);
      }
    },
    removeHistoryEvent(state, eventId) {
      const eventIndex = state.history.events.findIndex((e) => e.id === eventId);
      if (eventIndex > -1) {
        const removedEvent = state.history.events.splice(eventIndex, 1)[0];
        console.log(`🗑️ 删除历史事件: ${removedEvent.summary} (ID: ${eventId})`);
        console.log(`📊 剩余历史事件总数: ${state.history.events.length}`);
        
        // 保存到本地存储
        const userStorage = require("../utils/userStorage").default;
        userStorage.setItem("gameHistory", state.history.events);
      } else {
        console.warn(`⚠️ 未找到要删除的历史事件: ${eventId}`);
      }
    },
    setCurrentRound(state, round) {
      state.history.currentRound = round;
    },
    setCurrentPhase(state, phase) {
      console.log(`🔄 setCurrentPhase: ${phase}, currentRound: ${state.history.currentRound}`);
      state.history.currentPhase = phase;

      // 自动更新轮次
      if (phase === "day" && state.history.currentRound === 1) {
        // 第一个白天
        state.history.currentRound = "first_day";
        console.log(`✅ 设置为第一个白天: ${state.history.currentRound}`);
      } else if (phase === "night" && state.history.currentRound === 1) {
        // 首夜
        state.history.currentRound = "first_night";
        console.log(`✅ 设置为首夜: ${state.history.currentRound}`);
      } else if (
        phase === "day" &&
        typeof state.history.currentRound === "number"
      ) {
        // 后续白天（数字类型）
        const roundNumber = state.history.currentRound;
        console.log(`🔢 数字轮次转换为白天: ${roundNumber}`);
        if (roundNumber === 1) {
          state.history.currentRound = "first_day";
          console.log(`✅ 数字1→first_day: ${state.history.currentRound}`);
        } else {
          state.history.currentRound = `${getChineseNumber(roundNumber)}_day`;
          console.log(`✅ 数字${roundNumber}→${state.history.currentRound}`);
        }
      } else if (
        phase === "night" &&
        typeof state.history.currentRound === "number"
      ) {
        // 后续夜晚（数字类型）
        const roundNumber = state.history.currentRound;
        console.log(`🔢 数字轮次转换为夜晚: ${roundNumber}`);
        if (roundNumber === 1) {
          state.history.currentRound = "first_night";
          console.log(`✅ 数字1→first_night: ${state.history.currentRound}`);
        } else {
          state.history.currentRound = `${getChineseNumber(roundNumber)}_night`;
          console.log(`✅ 数字${roundNumber}→${state.history.currentRound}`);
        }
      } else if (
        phase === "day" &&
        state.history.currentRound &&
        state.history.currentRound.includes("night")
      ) {
        // 从夜晚切换到白天，增加轮次
        const currentRound = state.history.currentRound;
        console.log(`🌙→☀️ 从夜晚切换到白天, 当前轮次: ${currentRound}`);
        if (currentRound === "first_night") {
          state.history.currentRound = "first_day";
          console.log(`✅ 首夜→第一个白天: ${state.history.currentRound}`);
        } else {
          // 提取轮次标识符（如"second", "third"等）
          const roundMatch = currentRound.match(/(.+)_night/);
          if (roundMatch) {
            const roundIdentifier = roundMatch[1];
            const roundNumber = getNumberFromChinese(roundIdentifier);
            if (roundNumber) {
              state.history.currentRound = `${getChineseNumber(roundNumber)}_day`;
              console.log(`✅ ${currentRound}→${state.history.currentRound} (${roundIdentifier}→数字${roundNumber})`);
            } else {
              console.error(`❌ 无法解析夜晚轮次标识符: ${roundIdentifier}`);
            }
          } else {
            console.error(`❌ 无法匹配夜晚轮次格式: ${currentRound}`);
          }
        }
      } else if (
        phase === "night" &&
        state.history.currentRound &&
        state.history.currentRound.includes("day")
      ) {
        // 从白天切换到夜晚，增加轮次
        const currentRound = state.history.currentRound;
        console.log(`☀️→🌙 从白天切换到夜晚, 当前轮次: ${currentRound}`);
        if (currentRound === "first_day") {
          state.history.currentRound = "second_night";
          console.log(`✅ 第一个白天→第二个夜晚: ${state.history.currentRound}`);
        } else {
          // 提取轮次标识符（如"second", "third"等）
          const roundMatch = currentRound.match(/(.+)_day/);
          if (roundMatch) {
            const roundIdentifier = roundMatch[1];
            const roundNumber = getNumberFromChinese(roundIdentifier);
            if (roundNumber) {
              const nextRoundNumber = roundNumber + 1;
              const newRound = `${getChineseNumber(nextRoundNumber)}_night`;
              state.history.currentRound = newRound;
              console.log(`✅ ${currentRound}→${newRound} (${roundIdentifier}→数字${roundNumber}+1=${nextRoundNumber})`);
            } else {
              console.error(`❌ 无法解析白天轮次标识符: ${roundIdentifier}`);
            }
          } else {
            console.error(`❌ 无法匹配白天轮次格式: ${currentRound}`);
          }
        }
      } else {
        console.warn(`⚠️ 未匹配的阶段切换情况: phase=${phase}, currentRound=${state.history.currentRound} (类型: ${typeof state.history.currentRound})`);
      }
      
      console.log(`🏁 阶段切换完成: ${phase}, 最终轮次: ${state.history.currentRound}`);
    },
    loadHistoryFromStorage(state) {
      const userStorage = require("../utils/userStorage").default;
      const savedHistory = userStorage.getItem("gameHistory");
      if (savedHistory) {
        try {
          state.history.events = savedHistory;
        } catch (e) {
          console.warn("Failed to load history from storage:", e);
        }
      }
    },
    clearHistory(state) {
      state.history.events = [];
      const userStorage = require("../utils/userStorage").default;
      userStorage.removeItem("gameHistory");
    },
    checkNewGame(state) {
      // 检查是否有历史记录
      if (state.history.events.length > 0) {
        return true; // 需要询问是否清除
      }
      return false;
    },
    resetGameState(state) {
      // 重置游戏状态
      state.history.currentRound = 1;
      state.history.currentPhase = "night";
    },
    setSelectedPlayer(state, index) {
      state.selectedPlayer = index;
    },
  },
  plugins: [persistence, socket],
});

